﻿//using CcpMigration.Models;
//using Microsoft.AspNet.Hosting;
//using Microsoft.AspNet.Identity;
//using Microsoft.Extensions.Caching.Distributed;
//using Microsoft.Extensions.Configuration;
//using Microsoft.Extensions.DependencyInjection;
//using Microsoft.Extensions.Logging;
//using Microsoft.Extensions.PlatformAbstractions;
//using Sino.CapacityCloud.Infrastructure.Services;
//using Sino.CapacityCloud.Repositories.Models;
//using System;
//using System.Diagnostics;
//using System.Net.Http;
//using System.Threading.Tasks;

//namespace Sino.CapacityCloud.Services
//{

//    public class OldCcpDataSyncWorker
//         : BackgroundWorker, IOldCcpDataSyncWorker
//    {

//        public const string ConfigurationFileName = "appsettings";

//        private static int InstanceCount = 0;

//        private readonly IDistributedCache _cache;
//        private readonly ITmsServiceBus _tmsServiceBus;
//        private readonly IServiceProvider _serviceProvider;
//        private readonly IBankCardService _bankCard;
//        private readonly IAzureStorageService _azureStorage;

//        public IConfiguration Configuration { get; }

//        public string RmsDbConnectionString { get; }

//        public string BlobBaseUrl { get; }

//        public string DomainName { get; }

//        public OldCcpDataSyncWorker(
//            ILoggerFactory loggerFactory,
//            IApplicationEnvironment appEnv,
//            IHostingEnvironment env,
//            IDistributedCache cache,
//            ITmsServiceBus tmsServiceBus,
//            IBankCardService bankCard,
//            IAzureStorageService azureStorage,
//            IServiceProvider serviceProvider)
//            : base(loggerFactory)
//        {
//            this._cache = cache;
//            this._tmsServiceBus = tmsServiceBus;
//            this._bankCard = bankCard;
//            this._serviceProvider = serviceProvider;
//            this._azureStorage = azureStorage;

//            var configurationBuilder = new ConfigurationBuilder()
//                 .SetBasePath(appEnv.ApplicationBasePath)
//                .AddJsonFile($"{ConfigurationFileName}.json")
//                .AddJsonFile($"{ConfigurationFileName}.{env.EnvironmentName}.json", optional: true)
//                .AddEnvironmentVariables();

//            this.Configuration = configurationBuilder.Build();
//            this.DomainName = this.Configuration["AppSettings:DomainName"];
//            var section = this.Configuration.GetSection("Data:DefaultConnection:OldTms");
//            this.RmsDbConnectionString = section["RmsDbConnectionString"]?.Replace("|DataDirectory|", env.MapPath("App_Data\\")) ?? "";
//            this.BlobBaseUrl = section["BlobBaseUrl"];

//            this._logger.LogInformation($"Starting {nameof(OldCcpDataSyncWorker)} {InstanceCount++}");

//            this.Start();
//        }

//        public override void Start()
//        {
//            base.Start();
//        }

//        protected async override Task<bool> Process()
//        {
//            try
//            {
//                using (var serviceScope = this._serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
//                {
//                    using (var dbContext = serviceScope.ServiceProvider.GetService<ApplicationDbContext>())
//                    {
//                        using (var userManager = serviceScope.ServiceProvider.GetService<ApplicationUserManager>())
//                        {
//                            using (var db = new RmsdbContext(this.RmsDbConnectionString))
//                            {
//                                if (db.Database.Exists())
//                                {
//                                    foreach (var carrier in db.CarrierTab)
//                                    {
//                                        if (carrier.UserName != null)
//                                        {
//                                            this._logger.LogInformation($"Copying user {carrier.UserName}...");
//                                            var user = await userManager.FindByPhoneNumberAsync(carrier.UserName);
//                                            if (user == null)
//                                            {
//                                                this._logger.LogInformation($"Creating new driver user {carrier.UserName}...");
//                                                user = await userManager.CreateUserAsync(
//                                                    carrier.UserName, carrier.UserName + $"@{this.DomainName}",
//                                                    carrier.UserName, new[] { ApplicationRole.Driver });
//                                                if (user == null)
//                                                {
//                                                    this._logger.LogError($"Failed to create new driver user {carrier.UserName}.");
//                                                    continue;
//                                                }
//                                            }
//                                            else
//                                            {
//                                                this._logger.LogInformation($"The user {carrier.UserName} has been here. Update it.");
//                                            }

//                                            string avatarFileName = null;
//                                            carrier.PhotosUrl = this.GenerateRemoteSourceImageUrl(carrier.PhotosUrl, ref avatarFileName);

//                                            string idCardFileName = null;
//                                            carrier.cardUrl = this.GenerateRemoteSourceImageUrl(carrier.cardUrl, ref idCardFileName);

//                                            carrier.Remarks = this.GenerateRemoteSourceImageUrl(carrier.Remarks);

//                                            user.CertificatePhotoKey = await this.UploadToAzureBlobAsync(carrier.PhotosUrl,
//                                                "avatar-container", avatarFileName);
//                                            user.IdentityCardKey = await this.UploadToAzureBlobAsync(carrier.cardUrl,
//                                                "realname-container", idCardFileName);
//                                            user.RealName = carrier.UserRealName;
//                                            user.Profile = carrier.Remarks;

//                                            if (carrier.approveState == "已认证")
//                                            {
//                                                user.CertificatePhotoCertificationState = CertificationStatus.Passed;
//                                                user.IdentityCardCertificationState = CertificationStatus.Passed;
//                                                user.CertificationTime = DateTime.Now;
//                                            }

//                                            await userManager.UpdateAsync(user);

//                                            await this._bankCard.AddBankCardAsync(dbContext, user, user.RealName, carrier.CardID);
//                                        }
//                                        else
//                                        {
//                                            // TODO: Add support to Carrier.
//                                        }
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//            catch (Exception ex)
//            {
//                this._logger.LogError($"Failed to add bank card because: {ex.Message + Environment.NewLine + ex.StackTrace}");
//            }
//            await Task.Delay(TimeSpan.FromDays(1));
//            return await Task.FromResult(true);
//        }

//        private string GenerateRemoteSourceImageUrl(string imgPath)
//        {
//            string fileName = null;
//            return this.GenerateRemoteSourceImageUrl(imgPath, ref fileName);
//        }

//        private string GenerateRemoteSourceImageUrl(string imgPath, ref string fileName)
//        {
//            if (!string.IsNullOrEmpty(imgPath) && imgPath.StartsWith("../Files/Car/"))
//            {
//                var relativePath = imgPath.Replace("../Files/Car/", "");
//                fileName = System.IO.Path.GetFileName(imgPath.Replace("../Files/Car/", ""));
//                return string.IsNullOrEmpty(imgPath) ? "" : this.BlobBaseUrl + relativePath;
//            }
//            return imgPath;
//        }

//        private async Task<string> UploadToAzureBlobAsync(string url, string container, string fileName, bool withQueryString = false)
//        {
//            try
//            {
//                if (string.IsNullOrEmpty(url))
//                {
//                    return null;
//                }
//                var sas = await this._azureStorage.GenerateShareAccessSignitureAsync(container);
//                var azureBlobUrl = await this._azureStorage.GetBlobItemUriAsync(sas, fileName, false);
//                if (azureBlobUrl != null)
//                {
//                    return azureBlobUrl;
//                }
//                using (var client = new HttpClient())
//                {
//                    using (var responseStream = await client.GetStreamAsync(url))
//                    {
//                        azureBlobUrl = await this._azureStorage.UploadBlobAsync(sas, fileName, responseStream);
//                        if (withQueryString)
//                        {
//                            return azureBlobUrl;
//                        }
//                        else
//                        {
//                            var azureBlobUri = new Uri(azureBlobUrl);
//                            return azureBlobUrl.Replace(azureBlobUri.Query, "");
//                        }
//                    }
//                }
//            }
//            catch (Exception ex)
//            {
//                this._logger.LogError($"Failed to upload {url} to container {container} because: {ex.Message + Environment.NewLine + ex.StackTrace}");
//                return url;
//            }
//        }

//    }

//}